package com.services;

import com.controllers.ClientController;
import com.models.Client;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class AuthService implements UserDetailsService {

  @Autowired
  private ClientController clientController;

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    Client user = clientController.getClient(username);
    User userDetail = new User(user.getUsername(), user.getPassword(), true, true, true, true, getAuthorities(user.getRole()));
    return userDetail;
  }

  public List<GrantedAuthority> getAuthorities(Integer role) {
    List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
    if (role == 1) {
      authList.add(new SimpleGrantedAuthority("ROLE_USER"));
      authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
    } else if (role == 2) {
      authList.add(new SimpleGrantedAuthority("ROLE_USER"));
    }
    return authList;
  }

  public Client getAuthenticatedUser() {
    Client user = (Client) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    return clientController.getClient(user.getUsername());
  }

}
